#!/usr/bin/env python
# -*- coding:utf-8 -*- #
import sys
import os
import atexit
from multiprocessing import Process,Queue
import threading

from conf import configure
from watch.watch import confMonitor
from core.cmdloader import CmdLoader
from core.processmanager import ProcessManager
from worktype import Monitor, Alarm, Logger

class Probe(object):
    '''
    探针运行主程序
    '''
    def __init__(self):
        #保存数据采集项内容
        self.monitor = None
        #保存监控项内容
        self.alarm = None
        self.processmanager = None
        self.conf_info = configure.cmdconfig
        self.object_cmdloader = CmdLoader() #实例化对象
        self.event = threading.Event()

    def run(self):
        if not configure.DEBUG:
            pidfile = 'pidfile'
            self.set_daemonize(True, pidfile)
            atexit.register(lambda:os.remove(pidfile))
        else:
            print 'debug: pid is: %s' % os.getpid()

        
        #启动一个线程进行配置文件的监控
        watch_conf = Process(target=confMonitor, args=(self.event,os.path.join(configure.ROOT,'conf')))
        watch_conf.start()
        
        self.processmanager = ProcessManager()
        #将监控事项载入分析
        
        self.object_cmdloader.load(self.conf_info)  #将配置字典给cmloader文件的load函数处理
        
        self.start_work()
        
        #监控文件更改后，重载配置文件,未完成
        #self.loop()
        
    def start_work(self):
        '''
        对分析数据，进行任务分配
        '''
        if self.conf_info.get('monitorcfg'):
            '''
            monitorcfg_detail = 
            {'disk_space': 
            {'fun': <function get_disk_space at 0xb7b7a95c>, 
            'rate': (1, (30, 60, 120, 180)), 
            'inet': <core.network.ShortConnection object at 0xb7c8fb2c>, 
            'id': 21, 
            'param': {'WarningData': 10}}
            }
            '''
            monitorcfg_detail = self.object_cmdloader.detail('monitorcfg')
            if not self.monitor:
                self.monitor = Monitor(self.processmanager, monitorcfg_detail)
            self.monitor.load_config(monitorcfg_detail)
            
        if self.conf_info.get('alarmcfg'):
            alarmcfg_detail = self.object_cmdloader.detail('alarmcfg')
            print "alarmcfg_detail ==",alarmcfg_detail
            if not self.alarm:
                self.alarm = Alarm(self.processmanager, alarmcfg_detail)
            self.alarm.load_config(alarmcfg_detail)
        if self.conf_info.get('loggercfg'):
            loggercfg_detail = self.object_cmdloader.detail('loggercfg')
            if not self.logger:
                self.logger = Logger(self.processmanager, loggercfg_detail)
            self.logger.load_config(loggercfg_detail)
        
    def reload_config(self):
        
        self.processmanager.recycle_all()
        import time
        time.sleep(3)

        if self.alarm:
            
            self.alarm.reset()
        reload(configure)
        self.object_cmdloader.reload_config(configure.cmdconfig)
        self.start_work(configure)

    def loop(self):
        """check event isSet every 5 seconds"""
        
        while True:
            
            self.event.wait(5)
            if self.event.isSet():
                self.reload_config()
                self.event.clear()

if __name__ == '__main__':
    probe = Probe()
    probe.run()
